package cn.com.shopec.erp.system.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.utils.DateUtil;
import cn.com.shopec.erp.common.utils.MD5Util;
import cn.com.shopec.erp.core.base.controller.BaseController;
import cn.com.shopec.erp.system.common.UserUtils;
import cn.com.shopec.erp.system.constant.SystemConstant;
import cn.com.shopec.erp.system.service.IAccessService;
import cn.com.shopec.erp.system.service.IUserService;
import cn.com.shopec.erp.system.vo.AccessVo;
import cn.com.shopec.erp.system.vo.UserVo;

/**
 * @Title: MainController
 * @Package: com.broadengate.core.system.controller
 * @Description: 系统后台Frame框架页面跳转类
 * @version V1.0
 */
@Controller
@RequestMapping("/manager/system/main")
public class MainController extends BaseController {

	Logger logger = Logger.getLogger(MainController.class);
	
	@Resource private IUserService userService;
	@Resource private IAccessService accessService;


	/**
	 * 转到首页
	 * 
	 * @return
	 */
	@RequestMapping("/tologin")
	public ModelAndView tologin(Map<String, Object> map) {
		return new ModelAndView("system/tologin");
	}

	/**
	 * 转到首页
	 * 
	 * @return
	 */
	@RequestMapping("/toIndex")
	public ModelAndView toIndex(Map<String, Object> map) {
		return new ModelAndView("system/login");
	}

	/**
	 * 登录
	 * 
	 * @param loginName
	 *            用户名称
	 * @param loginPassword
	 *            用户密码
	 * @param validateCode
	 *            验证码
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/login")
	public ModelAndView login(String loginName, String loginPassword,
			String validateCode, String cookieTime, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) throws Exception {
		Map<String, Object> warnMap = new HashMap<String, Object>();
		String indexUrl = "system/login";
		UserVo userVo = userService.getUserVoByLoginName(loginName);
		if (null == userVo) {
			warnMap.put("warnMessagekey", SystemConstant.LOGINUSER_NOT_EXISTS);
			return new ModelAndView(indexUrl, warnMap);
		}
		if (userVo.getEnableTime()!=null) {
			long minutes=userVo.getEnableTime().getTime() - new Date().getTime();
			if(minutes>0){
				warnMap.put("warnMessagekey", SystemConstant.LOGINUSER_IS_LUCKED_DATE+",解锁还剩："+new Date(minutes).getMinutes()+"分钟！");
				return new ModelAndView(indexUrl, warnMap);
			}
		}
		if (userVo.getLoginCount() >= SystemConstant.USER_LOGIN_COUNT) {
			userVo.setUserStatus(SystemConstant.USER_STATUS_1);
			userVo.setLoginCount(0);
			userVo.setEnableTime(new Date(new Date().getTime() + 600000));
			userService.modifyUser(userVo);
			warnMap.put("warnMessagekey", SystemConstant.LOGINUSER_IS_LUCKED);
			return new ModelAndView(indexUrl, warnMap);
		}
		if (userVo.getUserStatus() == SystemConstant.USER_STATUS_2) {
			modifyUserLoginCount(userVo);
			warnMap.put("warnMessagekey", SystemConstant.LOGINUSER_IS_LUCKED);
			return new ModelAndView(indexUrl, warnMap);
		}
		if (userVo.getDeleteFlag() == SystemConstant.DELETE_FLAG_0) {
			modifyUserLoginCount(userVo);
			warnMap.put("warnMessagekey", SystemConstant.LOGINUSER_IS_DELETED);
			return new ModelAndView(indexUrl, warnMap);
		}
		//if (!userVo.getPwd().equals(MD5Util.MD5Encode(null == loginPassword ? "" : loginPassword, SystemConstant.CHARSET_UTF8))) {
		if (userVo.getPwd().equalsIgnoreCase(loginPassword)) {
			modifyUserLoginCount(userVo);
			warnMap.put("warnMessagekey", SystemConstant.PASSWORD_NOT_CORRECT);
			return new ModelAndView(indexUrl, warnMap);
		}
		userVo.setLoginCount(0);//登录成功次数还原
		userService.modifyUser(userVo);
		HttpSession session = request.getSession();
		session.setAttribute(SystemConstant.LOGINUSER_SESSION, userVo);
		return new ModelAndView("redirect:mainFrame.do");
	}
	
	/**
	 * 用户登录次数自增
	 * @param userVo
	 */
	public void modifyUserLoginCount(UserVo userVo){
		try {
			userVo.setLoginCount(userVo.getLoginCount()+1);//登录次数自增
			userService.modifyUser(userVo);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	

	/**
	 * 系统管理入口
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("mainFrame")
	public ModelAndView mainFrame(HttpServletRequest request,
			ModelMap map) throws Exception {
		UserVo userVo = UserUtils.getUserVo(request);
		if (null == userVo) {
			return new ModelAndView("redirect:toIndex.do");
		}
		map.put("userVo", userVo);
		return new ModelAndView("system/main", map);
	}

	/**
	 * 注销
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,
			HttpServletResponse response) {
		request.getSession().invalidate();
		return "redirect:toIndex.do";
	}

	@RequestMapping("/mainLeft")
	public ModelAndView manageLfbar(ModelMap map, HttpServletRequest request) {
		return new ModelAndView("system/main_left", map);
	}

	@RequestMapping("/mainCenter")
	public String mainCenter() {
		return "system/main_center";
	}

	@RequestMapping("/mainTop")
	public String mainTop() {
		return "system/main_top";
	}

	@RequestMapping("/bottom")
	public String bottom() {
		return "system/bottom";
	}
	
	@RequestMapping("error")
	public String error() {
		return "system/error";
	}

	/**
	 * 没有权限提示页
	 * 
	 * @return
	 */
	@RequestMapping("/noPrivilege")
	public ModelAndView noPrivilege() {
		return new ModelAndView("system/noPrivilege");
	}

	@RequestMapping("welcome")
	public ModelAndView welcome(ModelMap modelMap, HttpServletRequest request) {
		//modelMap.put("exceptionICs", InventoryChangeScheduler.getExceptionIC().size());
		return new ModelAndView("system/welcome");
	}
	
	/**
	 * 检查验证码是否正确
	 * 
	 * @return String
	 */
	@RequestMapping("validateCode")
	@ResponseBody
	public String validateCode(String code, HttpServletRequest request) {
		String sCode = (String) request.getSession().getAttribute(SZSCMConstant.LOGIN_VALIDATE_IMAGE);
		if (code.equals(sCode)) {
			return SystemConstant.SUCCESS;
		} else {
			return SystemConstant.FAIL;
		}
	}
	
	/**
	 * 加载属于自己的菜单树
	 * 
	 * @return String
	 */
	@RequestMapping("loadOwnTree")
	@ResponseBody
	public String loadOwnTree(HttpServletRequest request) throws Exception {
		UserVo userVo = UserUtils.getUserVo(request);
		List<AccessVo> accessVos = accessService.loadOwnTree(userVo);
		return JSONObject.toJSONString(accessVos);
	}
	
}
